﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using TeamTime.Classes;
using StillVoiceCommon;

namespace TeamTime
{
    public partial class TaskFormControl : System.Web.UI.UserControl
    {
        public string SaveButtonText { get { return this.btnSave.Text; } set { this.btnSave.Text = value; } }

        public bool SaveButtonVisible { get; set; }
        //private bool liteMode;


        public bool SuccessfullySaved
        {
            get { return this.chkSuccessfullySaved.Checked; }
            set { this.chkSuccessfullySaved.Checked = value; }
        }
        public Int32 CompanyID
        {
            get
            {
                if (this.txtCompanyID.Text == "") this.txtCompanyID.Text = "0";
                return Convert.ToInt32(this.txtCompanyID.Text);
            }
            set
            {
                this.txtCompanyID.Text = value.ToString();
            }
        }
        public Int32 TaskID
        {
            get { return Convert.ToInt32(this.txtID.Text); }
            set
            {
                //this.txtID.Text = .ToString();
                LoadDetailsForm(value);
            }
        }

        public event System.EventHandler SaveClicked;
        private void TaskFormControl_SaveClicked(object sender, EventArgs e) { }
        public delegate void SaveClickEventHandler(object sender, EventArgs e);

        public event System.EventHandler LoadDupClicked;
        private void TaskFormControl_LoadDupClicked(object sender, EventArgs e) { }
        public delegate void LoadDupClickEventHandler(object sender, EventArgs e);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                TN5YProjects tn5yProjects = new TN5YProjects();
                Functions.dropDownListPopulate(this.ddlProjectID, tn5yProjects.getProjects(false), "ID", "CompanyProject");
                StaffMembers staffMembers = new StaffMembers();
                if (ddlStaffMemberIDAllocatedTo.Items.Count == 0)
                    Functions.dropDownListPopulate(this.ddlStaffMemberIDAllocatedTo, staffMembers.getStaffMembers(true), "ID", "FullName");

                EnableControls();
               // this.lnkAddTime.Enabled = false;
                
            }

           
                                  
               

        }


        private void BindGrid()
        {
            Tasks tasks = new Tasks();
            GridView1.DataSource = tasks.getTimeEntriesFromTaskID(TaskID);
            GridView1.DataBind();
            decimal tot = 0;
            if (GridView1.Rows.Count > 0)
            {
                foreach (GridViewRow r in GridView1.Rows)
                {
                    tot += Convert.ToDecimal(((Label)r.FindControl("lblHours")).Text);
                }
                ((Label)this.GridView1.HeaderRow.FindControl("lblTotalHours")).Text = tot.ToString("0.00");
            }
            if (this.LoadDupClicked != null)
                this.LoadDupClicked(this, null);
          
        }

        public void EnableControls()
        {
            Functions.enableChildControls(this.pnlDetails);
            this.txtUserNameModifiedBy.Enabled = true;
            this.txtRecordDate.Enabled = true;
            this.trID.Visible = (txtID.Text != "");
            this.txtID.Enabled = false;
        }
        public void setForAdding()
        {
            Functions.clearChildcontrols(this.pnlDetails);
            this.calCreationDate.Text = DateTime.Now.ToString("yyyy/MM/dd");

            //Users user = new Users();
            //Int32 PersonID = user.getPersonIDFromUser(Session["UserID"].ToString());
            //ddlStaffMemberIDAllocatedTo.SelectedValue = Convert.ToString(user.getIDFromViewStaffMembers(PersonID));
            StaffMembers staffMembers = new StaffMembers();
            if (ddlStaffMemberIDAllocatedTo.Items.Count == 0)
                Functions.dropDownListPopulate(this.ddlStaffMemberIDAllocatedTo, staffMembers.getStaffMembers(true), "ID", "FullName");

            Int32 staffMemberID = staffMembers.getStaffMemberIDFromUserID(Convert.ToInt32(Session["UserID"]));
            ddlStaffMemberIDAllocatedTo.SelectedValue = staffMemberID.ToString();
            this.lblURL.Visible = true;
        }
        private void LoadDetailsForm(Int32 ID)
        {
            Task task = new Task();
            task.load(ID.ToString());
            TimeEntries timeEntry = new TimeEntries();
            Functions.populateFormControlsFromDataTableFields(task, this.pnlDetails);
            this.hypURL.NavigateUrl = task.Fields["URL"].ToString();
            this.hypURL.Text = task.Fields["URL"].ToString();
            if (hypURL != null)
                    {
                        this.lblURL.Visible = false;
                    }
            BindGrid();
            EnableControls();
            
           
        }
        public void btnSave_Click(object sender, EventArgs e)
        {
            SuccessfullySaved = false;
            this.lnkLoadDup.Attributes["DupID"] = "";
            this.lnkLoadDup.Visible = false;
            Tasks tasks = new Tasks();
            this.txtTaskName.Text = this.txtTaskName.Text.Trim();
            int dupID = tasks.getDuplicateTaskID(this.txtTaskName.Text, Convert.ToInt32(this.ddlProjectID.SelectedValue), this.txtID.Text);
            if (dupID != 0)//Duplicate exists
            {
                this.lnkLoadDup.Attributes["DupID"] = dupID.ToString();
                this.lnkLoadDup.Visible = true;
                if (this.LoadDupClicked != null)
                    this.LoadDupClicked(sender, e);
            }
            else //Save
            {
                Task task = new Task();
                if (this.txtID.Text == "") { task.setForAdd(); } else { task.load(this.txtID.Text); }

                task.Fields["TaskName"] = this.txtTaskName.Text;
                task.Fields["Description"] = this.txtDescription.Text;
                if (this.calCreationDate.Text != "") task.Fields["CreationDate"] = this.calCreationDate.Text; else task.Fields["CreationDate"] = DBNull.Value;
                task.Fields["Disabled"] = Math.Abs(Convert.ToInt16(this.chkDisabled.Checked));
                task.Fields["EstimatedHours"] = this.txtEstimatedHours.Text;
                if (this.calCompletionDate.Text != "") task.Fields["CompletionDate"] = this.calCompletionDate.Text; else task.Fields["CompletionDate"] = DBNull.Value;
                task.Fields["ProjectID"] = this.ddlProjectID.SelectedValue;
                task.Fields["StaffMemberIDAllocatedTo"] = this.ddlStaffMemberIDAllocatedTo.SelectedValue;
                task.Fields["CustomerRefNumber"] = this.txtCustomerRefNumber.Text;
                task.Fields["URL"] = this.txtURL.Text;


                task.UserIDModifiedBy = Convert.ToInt32(Session["UserID"]);
                task.updateWithUserIDDate(); //Updates RecordDate
                this.TaskID = Convert.ToInt32(task.KeyValue);
                //if (this.CompanyID != 0)
                //{
                //    task.AddToCompany(CompanyID);
                //}

                SuccessfullySaved = true;
                lblSaveMessage.ShowStatusMessage("Successfully saved");

                LoadDetailsForm(Convert.ToInt32(task.KeyValue));
                if (this.SaveClicked != null)
                    this.SaveClicked(sender, e);
                task = null;
                this.lnkAddTime.Visible = true;
            }
        }

        protected void lnkAddTime_Click(object sender, EventArgs e)
        {
            btnSave_Click(sender, e);
            Response.Redirect("TimeEntriesForm.aspx?TaskID=" + this.txtID.Text);
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                Response.Redirect("TimeEntriesForm.aspx?ID=" + e.CommandArgument.ToString());
            }
            //if (e.CommandName == "Add")
            //{

            //    Response.Redirect("TimeEntriesForm.aspx?addmode=" + e.CommandArgument.ToString());
            //}

        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView theGrid = sender as GridView;  // refer to the GridView
            int newPageIndex = 0;

            if (-2 == e.NewPageIndex)
            { // when click the "GO" Button
                TextBox txtNewPageIndex = null;
                //GridViewRow pagerRow = theGrid.Controls[0].Controls[theGrid.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
                GridViewRow pagerRow = theGrid.BottomPagerRow; //


                if (null != pagerRow)
                {
                    txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;   // refer to the TextBox with the NewPageIndex value
                }

                if (null != txtNewPageIndex)
                {
                    newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
                }
            }
            else
            {  // when click the first, last, previous and next Button
                newPageIndex = e.NewPageIndex;
            }

            // check to prevent form the NewPageIndex out of the range
            newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
            newPageIndex = newPageIndex >= theGrid.PageCount ? theGrid.PageCount - 1 : newPageIndex;

            // specify the NewPageIndex
            theGrid.PageIndex = newPageIndex;

            // display a new page of data
            // GridView1.EditIndex = -1;
            //GridView1.PageIndex = e.NewPageIndex;
            BindGrid();
            // rebind the control
            // in this case of retrieving the data using the xxxDataSoucr control,
            // just do nothing, because the asp.net engine binds the data automatically
        }

        protected string formatNum(object fld)
        {
            if (fld == DBNull.Value)
            {
                return "";

            }
            else
            {
                return Convert.ToDecimal(fld).ToString("0.00");
            }


        }

        protected void lnkLoadDup_Click(object sender, EventArgs e)
        {
            if (this.lnkLoadDup.Attributes["DupID"] != "")
            {
                LoadDetailsForm(Convert.ToInt32(this.lnkLoadDup.Attributes["DupID"]));
                this.lnkLoadDup.Visible = false;
            }

            if (this.LoadDupClicked != null)
                this.LoadDupClicked(sender, e);
        }

        //private void Save()
        //{


        //}

    }
}